/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Shared/DB/MySQL/MySQLDatabase.h"
#include "Shared/DB/MySQL/MySQLSqlConnection.h"


namespace Shared {
namespace DB {

    bool Database::checkSanity(void)
    {
        return (mysql_thread_safe() != 0);
    }

namespace MySQL {

    MySQLDatabase::MySQLDatabase(void)
    {
        _conn.reset(new MySQLSqlConnection(*this));
        _asyncConn.reset(new MySQLSqlConnection(*this));
    }

    MySQLDatabase::~MySQLDatabase(void)
    {

    }

    bool MySQLDatabase::initialize(const std::string &host, const std::string &port,
        const ::std::string &user, const std::string &pass, const std::string &db, 
        bool autoReconnect /*= true*/)
    {
        SHARED_ASSERT(_conn.get() && _asyncConn.get());
        if (_conn->open(host, port, user, pass, db, autoReconnect) 
            && _asyncConn->open(host, port, user, pass, db, autoReconnect))
        {
            return Database::initialize(host, port, user, pass, db);
        }
        return false;
    }

    void MySQLDatabase::close(void)
    {
        Database::close();

        if (_conn.get()) {
            _conn->close();
            _conn.reset();
        }
        if (_asyncConn.get()) {
            _asyncConn->close();
            _asyncConn.reset();
        }
    }

    void MySQLDatabase::escapeString(::std::string &sql)
    {
        char lsql[MAX_QUERY_LENGTH];
        ::mysql_escape_string(lsql, sql.c_str(), sql.length());
        sql.clear();
        sql = lsql;
    }

    bool MySQLDatabase::reconnect(void)
    {
        return true;
    }

    void MySQLDatabase::ping(void)
    {
        SHARED_ASSERT(_conn.get() && _asyncConn.get());
        _conn->ping();
        _asyncConn->ping();
    }

}}}